package leetcode.day_2021_03_22_2021_03_28;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 76. 最小覆盖子串
 * https://leetcode-cn.com/problems/minimum-window-substring/
 */
public class LeetCode0076 {

    public static String minWindow(String s, String t) {
        Map<Character, Integer> window = new HashMap<>();
        Map<Character, Integer> need = new HashMap<>();

        for (char c : t.toCharArray()) {
            need.put(c, need.getOrDefault(c, 0) + 1);
        }
        int valid = 0, start = 0, minLen = Integer.MAX_VALUE;
        int left = 0, right = 0, length = s.length();
        while (right < length) {
            char c1 = s.charAt(right);
            right++;
            if (need.containsKey(c1)) {
                window.put(c1, window.getOrDefault(c1, 0) + 1);
                if (window.get(c1).equals(need.get(c1))) {
                    valid ++;
                }
            }

            while (valid == need.size()) {
                if (right - left < minLen) {
                    minLen = right - left;
                    start = left;
                }
                char c2 = s.charAt(left);
                left++;
                if (need.containsKey(c2)) {
                    if (need.get(c2).equals(window.get(c2))) {
                        valid --;
                    }
                    if (window.get(c2)-1 <= 0) {
                        window.remove(c2);
                    } else {
                        window.put(c2, window.get(c2) - 1);
                    }
                }
            }
        }
        return minLen == Integer.MAX_VALUE ? "" : s.substring(start, start+minLen);
    }

    public static void main(String[] args) {
        System.out.println(minWindow("ADOBECODEBANC", "ABC"));
    }
}
